﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using AjaxControlToolkit;
using com.paypal.soap.api;
using System.Data;
using System.Web.Security;
using ASPDotNetSamples;
using System.Text;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Web.UI.HtmlControls;

public partial class Front_UserControl_Deal : System.Web.UI.UserControl {

    private int DealID;
    public int _DealID {
        get {
            return DealID;
        }
        set {
            DealID = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e) {
        try {
            setSecureProtocol(false);
            if (!IsPostBack) {

                if (Session["SubscribeDaialyDeal"] != null) {

                    SubcribedCity.Text = " Welcome to Zupons " + Request.Cookies["CityName"].Value.ToString() + " !";
                    divSubcrigePopUp.Show();
                }

                BindRecord(DealID);

            }

        } catch (Exception ex) {
        }

    }
    public void setSecureProtocol(bool bSecure) {
        string redirectUrl = null;

        // if we want HTTPS and it is currently HTTP
        if (bSecure && !Request.IsSecureConnection)
            redirectUrl = Request.Url.ToString().Replace("http:", "https:");

        else

            // if we want HTTP and it is currently HTTPS
            if (!bSecure && Request.IsSecureConnection) redirectUrl = Request.Url.ToString().Replace("https:", "http:");

        //else

        // in all other cases we don't need to redirect

        // check if we need to redirect, and if so use redirectUrl to do the job
        if (redirectUrl != null)

            Response.Redirect(redirectUrl);

    }
    public void MakeSSLSecure() {
        string strURL = Request.Url.ToString();
        Array arrURL = strURL.Split('/');
        string strHttpPath;
        string strHttpsPath;
        Array arrHttpPath;
        strHttpPath = "http://" + arrURL.GetValue(2).ToString() + Request.ApplicationPath;
        strHttpsPath = "https://" + arrURL.GetValue(2).ToString() + Request.ApplicationPath;
        arrHttpPath = strHttpPath.ToCharArray();
        if (arrHttpPath.GetValue(strHttpPath.Length - 1).ToString() == "/") {
            strHttpPath = strHttpPath.Substring(0, strHttpPath.Length - 1);
            strHttpsPath = strHttpsPath.Substring(0, strHttpsPath.Length - 1);
        }
        //Session["HttpPath"] = strHttpPath; //When http path is required uncomment it and use this session value while redirecting it to other page.
        Session["HttpsPath"] = strHttpsPath;

    }

    protected void linkrefferFriend_Click(object sender, EventArgs e) {
        Response.Redirect("~/ReferFriend.aspx");
    }
    protected override void OnPreRender(EventArgs e) {
        double Second = 0.0;
        try {

            if (ViewState["endDT"] != null && ViewState["starDT"] != null) {
                Second = System.Data.Linq.SqlClient.SqlMethods.DateDiffSecond(Convert.ToDateTime(System.DateTime.Now), Convert.ToDateTime(ViewState["endDT"]));
                if (Second <= 0) {
                    if (Session["RecentDealID"] == null) {
                        timeCountDown.Visible = false;
                        //  Response.Redirect("NoDealExist.aspx");
                    } else {
                        timeCountDown.Visible = false;
                        Session["RecentDealID"] = null;
                    }
                } else {
                    hdnseconds.Value = Second.ToString();
                }
            } else {
                hdnseconds.Value = Second.ToString();
                Response.Redirect("NoDealExist.aspx");
            }

        } catch {
            hdnseconds.Value = Second.ToString();
            Response.Redirect("NoDealExist.aspx");
        }

    }
    public void RadAddressBox_ItemDataBound(object sender, RadListViewItemEventArgs e) {
        string address1 = RadAddressBox.DataKeyValues[0]["Address1"].ToString();
        string City = RadAddressBox.DataKeyValues[0]["City"].ToString();
        string State = RadAddressBox.DataKeyValues[0]["State"].ToString();
        UserControl Googlemap1 = (UserControl)e.Item.FindControl("Googlemap1");

    }
   private static string shareLink = string.Empty;
    private void BindRecord(int DealID) {
        try {
            if (Session["RecentDealID"] == null) {
                ViewState["endDT"] = null;
                ViewState["starDT"] = null;
                var deal = new DealesDataContext();
                var query = deal.SelectDeal_ByDealID(Convert.ToInt32(DealID));
                foreach (var item in query) {
                    Response.Cookies.Clear();
                    Response.Cookies["CityID"].Value = Convert.ToString(item.DealCityID);
                    Response.Cookies["CityID"].Expires = DateTime.Now.AddDays(30);
                    Response.Cookies["CityName"].Value = item.city.ToString();
                    Response.Cookies["CityName"].Expires = DateTime.Now.AddDays(30);
                    lblVendor.Text = item.VendorName.ToString();
                    lblDescription.Text = item.Description.ToString();
                    lblDealTitle.Text = item.Name;
                    //txtSubject.Text = item.Name;
                    //txtMessage.Text = item.Name;
                    shareLink = "<br/>\r\r https://www.zupons.com/default.aspx/DealID=" + item.DealID.ToString();
                    //txtMessage.Text += "\r\r https://www.zupons.com/default.aspx/DealID=" + item.DealID.ToString();
                    lblValue.Text = "$" + item.RegularPrice.ToString();
                    lblRegularPrice.Text = "$" + item.SellPrice.ToString();
                    lblDiscount.Text = item.Discount.ToString() + "%";
                    lblSave.Text = "$" + (Convert.ToDouble(item.RegularPrice) - Convert.ToDouble(item.SellPrice)).ToString();
                    DealImg.ImageUrl = "../Admin/ImageDisplay.aspx?DealID=" + item.DealID;
                    string EndDate = Convert.ToDateTime(item.SellEndDate.ToString()).ToShortDateString();
                    string EndTime = Convert.ToDateTime(item.SellEndTime.ToString()).ToShortTimeString();
                    DateTime starDT = Convert.ToDateTime(System.DateTime.Now);
                    DateTime endDT = Convert.ToDateTime(EndDate + " " + EndTime);
                    ViewState["endDT"] = endDT;
                    ViewState["starDT"] = starDT;
                    txtFootPrint.Text = item.FootPrint.ToString();
                    Session["DealID"] = item.DealID.ToString();
                    Session["CityID"] = item.DealCityID.ToString();
                    Session["VendorID"] = item.VendorID.ToString();
                    ViewState["DealID"] = item.DealID.ToString();
                    var VendorDetails = new DealesDataContext();
                    Twiteer.HRef = "https://twitter.com/home?status=" + item.Name + "- https://www.zupons.com/default.aspx";
                    FaceBook.HRef = "https://www.facebook.com/sharer.php?u=https://www.zupons.com/default.aspx?dealID=" + item.DealID.ToString();

                    var Vendor = VendorDetails.Select_VendorByID(Convert.ToInt32(item.VendorID.ToString()));
                    foreach (var items in Vendor) {
                        if (items.Address1.ToString() != "")
                            lblVendor.Text += "<br/>" + items.Address1.ToString() + "<br/>";
                        if (items.City.ToString() != "")
                            lblVendor.Text += items.City.ToString() + ", ";
                        if (items.State.ToString() != "")
                            lblVendor.Text += items.State.ToString() + " ";
                        if (items.ZipCode.ToString() != "")
                            lblVendor.Text += items.ZipCode.ToString();
                        if (items.Phone_Off_.ToString() != "")
                            lblVendor.Text += "<br/>" + items.Phone_Off_.ToString();
                        website.HRef = "http://" + items.Website.ToString();

                        lnkGoogleMap.HRef = "https://maps.google.com/maps?q=" + TrimDescription(items.Address1, items.City, items.State, items.ZipCode);
                        ucGoogleMap._Address1 = items.Address1;
                        ucGoogleMap._City = items.City;
                        ucGoogleMap._State = items.State;
                        ucGoogleMap._GID = items.VendorID.ToString();
                    }
                    var Oder = new DealesDataContext();
                    var TotaLQty = Oder.Select_OrderByDealID(item.DealID);
                    foreach (var items in TotaLQty) {

                        TotalPurchaseQty.Text = items.Total.ToString();
                        if (TotalPurchaseQty.Text != "") {
                            TotalPurchaseQty.Text += " Bought";
                        }

                        if (Convert.ToInt32(items.Total) >= Convert.ToInt32(item.MaxQty)) {
                            ImageButton1.Visible = false;
                            ImageButton2.Visible = true;
                        }
                    }
                    var DealAddress = new DealesDataContext();
                    var DealAddressList = DealAddress.Select_DealAddressByDealID(Convert.ToInt32(item.DealID.ToString()));
                    RadAddressBox.DataSource = DealAddressList;
                    RadAddressBox.DataBind();
                    if (RadAddressBox.Items.Count > 0)
                        Locations.Visible = true;
                    else
                        Locations.Visible = false;

                    var HighLights = DealAddress.Select_HighLight(Convert.ToInt32(item.DealID.ToString()));
                    foreach (var items in HighLights) {
                        lblHighlights.Text += "<li>" + items.HighLights.ToString() + "</li>";
                    }
                    var Sidedeal = new DealesDataContext();
                    var SideDealquery = Sidedeal.Select_SideDealByCityID(Convert.ToInt32(item.DealCityID), Convert.ToInt32(item.DealID));
                    RadListView RadListView2 = (RadListView)Page.Master.FindControl("RadListView2");
                    System.Web.UI.HtmlControls.HtmlTableRow SideDeal = (System.Web.UI.HtmlControls.HtmlTableRow)Page.Master.FindControl("SideDeal");
                    RadListView2.DataSource = SideDealquery;
                    RadListView2.DataBind();
                    if (RadListView2.Items.Count > 0)
                        SideDeal.Visible = true;
                    else
                        SideDeal.Visible = false;

                    if (Session["SideDeal"] != null) {
                        string CityID;
                        string MainDealID = "0";
                        if (Request.Cookies["CityID"] != null) {
                            CityID = Request.Cookies["CityID"].Value;
                            var sub = new DealesDataContext();
                            var getDealID = sub.Select_DealByCityIDNew(Convert.ToInt32(CityID));
                            foreach (var items in getDealID) {
                                MainDealID = items.DealID.ToString();

                            }
                        }

                        RadListView RadListViewMainDeal = (RadListView)Page.Master.FindControl("RadListViewMainDeal");
                        HtmlTableRow tdMainDeal = (HtmlTableRow)Page.Master.FindControl("tdMainDeal");

                        var Maindeal = new DealesDataContext();
                        var querys = Maindeal.SelectDeal_ByDealID(Convert.ToInt32(MainDealID));
                        RadListViewMainDeal.DataSource = querys;
                        RadListViewMainDeal.DataBind();
                        if (RadListViewMainDeal.Items.Count > 0) {
                            Session["SideDeal"] = null;
                            tdMainDeal.Visible = true;
                        } else
                            tdMainDeal.Visible = false;


                    }
                }


            } else {

                ViewState["endDT"] = null;
                ViewState["starDT"] = null;
                var RecentDeal = new DealesDataContext();
                var query = RecentDeal.Display_RecentDeal(DealID);
                foreach (var item in query) {

                    lblVendor.Text = item.VendorName.ToString();
                    lblDescription.Text = item.Description.ToString();
                    lblDealTitle.Text = item.Name;
                    lblValue.Text = "$" + item.RegularPrice.ToString();
                    lblRegularPrice.Text = "$" + item.SellPrice.ToString();
                    lblDiscount.Text = item.Discount.ToString() + "%";
                    lblSave.Text = "$" + (Convert.ToDouble(item.RegularPrice) - Convert.ToDouble(item.SellPrice)).ToString();
                    DealImg.ImageUrl = "../Admin/ImageDisplay.aspx?DealID=" + item.DealID;
                    string EndDate = Convert.ToDateTime(item.SellEndDate.ToString()).ToShortDateString();
                    string EndTime = Convert.ToDateTime(item.SellEndTime.ToString()).ToShortTimeString();
                    DateTime starDT = Convert.ToDateTime(System.DateTime.Now);
                    DateTime endDT = Convert.ToDateTime(EndDate + " " + EndTime);
                    ViewState["endDT"] = endDT;
                    ViewState["starDT"] = starDT;
                    txtFootPrint.Text = item.FootPrint.ToString();
                    Session["DealID"] = item.DealID.ToString();
                    Session["CityID"] = item.DealCityID.ToString();
                    Session["VendorID"] = item.VendorID.ToString();
                    ViewState["DealID"] = item.DealID.ToString();
                    Twiteer.HRef = "https://twitter.com/home?status=" + item.Name + "- https://www.zupons.com/default.aspx";
                    FaceBook.HRef = "https://www.facebook.com/sharer.php?u=https://www.zupons.com/default.aspx?dealID" + item.DealID.ToString();

                    var VendorDetails = new DealesDataContext();
                    var Vendor = VendorDetails.Select_VendorByID(Convert.ToInt32(item.VendorID.ToString()));
                    foreach (var items in Vendor) {
                        if (items.Address1.ToString() != "")
                            lblVendor.Text += "<br/>" + items.Address1.ToString() + "<br/>";
                        if (items.City.ToString() != "")
                            lblVendor.Text += items.City.ToString() + ", ";
                        if (items.State.ToString() != "")
                            lblVendor.Text += items.State.ToString() + " ";
                        if (items.ZipCode.ToString() != "")
                            lblVendor.Text += items.ZipCode.ToString();
                        if (items.Phone_Off_.ToString() != "")
                            lblVendor.Text += "<br/>" + items.Phone_Off_.ToString();
                        website.HRef = "http://" + items.Website.ToString();
                    }

                    var Oder = new DealesDataContext();
                    var TotaLQty = Oder.Select_OrderByDealID(item.DealID);
                    foreach (var items in TotaLQty) {

                        TotalPurchaseQty.Text = items.Total.ToString();
                        if (TotalPurchaseQty.Text != "") {
                            TotalPurchaseQty.Text += " Bought";
                        }


                    }
                    ImageButton1.Visible = false;
                    ImageButton2.Visible = true;
                    var deal = new DealesDataContext();
                    var query1 = deal.SelectDeal_ByDealID(Convert.ToInt32(DealID));
                    foreach (var item1 in query1) {
                        ImageButton1.Visible = true;
                        ImageButton2.Visible = false;
                    }

                    var DealAddress = new DealesDataContext();
                    var DealAddressList = DealAddress.Select_DealAddressByDealID(Convert.ToInt32(item.DealID.ToString()));
                    RadAddressBox.DataSource = DealAddressList;
                    RadAddressBox.DataBind();
                    var HighLights = DealAddress.Select_HighLight(Convert.ToInt32(item.DealID.ToString()));
                    foreach (var items in HighLights) {
                        lblHighlights.Text += "<li>" + items.HighLights.ToString() + "</li>";
                    }
                    var Sidedeal = new DealesDataContext();
                    var SideDealquery = Sidedeal.Select_SideDealByCityID(Convert.ToInt32(item.DealCityID), Convert.ToInt32(item.DealID));
                    RadListView RadListView2 = (RadListView)Page.Master.FindControl("RadListView2");
                    HtmlTableRow SideDeal = (HtmlTableRow)Page.Master.FindControl("SideDeal");
                    RadListView2.DataSource = SideDealquery;
                    RadListView2.DataBind();
                    if (RadListView2.Items.Count > 0)
                        SideDeal.Visible = true;
                    else
                        SideDeal.Visible = false;

                }
            }
        } catch {
        }
    }



    protected void ImageButton1_Click(object sender, ImageClickEventArgs e) {
        // MakeSSLSecure();
        Response.Redirect("OrderDetailNew.aspx?DealID=" + ViewState["DealID"].ToString());
        //Response.Redirect(Session["HttpsPath"].ToString() + "/OrderDetailNew.aspx?DealID=" + ViewState["DealID"].ToString());

    }
    protected string TrimDescription(string Address, string City, string State, string zipcode) {
        string add = Address + " " + City + " " + State + " " + zipcode;
        add = add.Replace(" ", "+");
        add += "&mrt=yp";
        return add;
    }
    protected string TrimDescription(string description) {
        if (!string.IsNullOrEmpty(description) && description.Length > 60) {
            return string.Concat(description.Substring(0, 60), "...");
        }
        return description;
    }
    protected void btnGiftSave_Click(object sender, EventArgs e)
    {
        //System.Collections.Specialized.ListDictionary replacements = new System.Collections.Specialized.ListDictionary();
        //replacements.Add("<%To%>", txtTo.Text.ToString());
        //replacements.Add("<%From%>", txtFrom.Text.ToString());
        //replacements.Add("<%Subject%>", txtSubject.Text.ToString());
        //replacements.Add("<%Message%>", txtMessage.Text.ToString());

        //System.Net.Mail.MailMessage confirmation = Mailer.CreateMessage(new System.Web.UI.Control() as WebControl,
        //    Mailer.MessageTemplate.Email, replacements, txtTo.Text.ToString(), "Email from Zupons");
        //Mailer.InternalSend(confirmation, false);
        string[] listOfTo = txtTo.Text.Trim().Split(',');
        string wouldYouLike = string.Format("<br/><br/>{0}&nbsp;<a href='{1}'>{2}</a>", "Would you like to", "https://www.zupons.com/default.aspx", "send another email");
        /*//Test sending email by gmail
        string _mailServer = "smtp.gmail.com";
        int _mailPort = 587;
        string _user = "hoangdo86@gmail.com";
        string _pass = "";
        string _mailFrom = "hoangdo86@gmail.com";

        MailMessage mailMessage = new MailMessage();
        SmtpClient mailClient = new SmtpClient(_mailServer, _mailPort);
        mailClient.Timeout = 15000;
        mailClient.Credentials = new NetworkCredential(_user, _pass);
        mailClient.EnableSsl = true;
        //mailClient.UseDefaultCredentials = true; // no work

        mailMessage.IsBodyHtml = true;
        mailMessage.From = new MailAddress(_mailFrom);
        mailMessage.Subject = "Email a Friend";
        mailMessage.Body = txtMessage.Text.ToString() + shareLink + wouldYouLike; 

        for (int i = 0; i < listOfTo.Length; i++)
        {
            mailMessage.To.Add(listOfTo[i]);
        }

        try
        {
            mailClient.Send(mailMessage);
            Response.Write("Send mail success");
        }
        catch (Exception ex)
        {
            Response.Write("Send mail fail, " + ex.Message);
        }
         */
       
        MailMessage Mail = new MailMessage();
        MailAddress ma = new MailAddress("mail@zupons.com", "Zupons");
        Mail.From = ma;

        for (int i = 0; i < listOfTo.Length; i++)
        {
            Mail.To.Add(listOfTo[i]);
        }

        Mail.Subject = "Email a Friend";
        Mail.Body = txtMessage.Text.ToString() + shareLink + wouldYouLike;
        Mail.IsBodyHtml = true;
        try
        {
            SmtpClient smtpMailObj = new SmtpClient();
            smtpMailObj.Host = "mail.zupons.com";
            smtpMailObj.Send(Mail);
            Response.Write("Your Message has been sent successfully");
        }
        catch (Exception ex)
        {
            Response.Write("Message Delivery Fails");
        }
    }

    protected void RadAddressBox_ItemDataBound1(object sender, RadListViewItemEventArgs e) {
        Label lblName = (Label)e.Item.FindControl("Name");

        //if (lblName.Text == "")
        //{
        //    lblName.Visible = false;
        //}
        //else
        //{
        //    lblName.Text +=" "+ "<br/>";
        //}
    }
}
